<template>
  <el-dialog
    class="login_dialog"
    v-model="showLogin"
    width="30%"
    :show-close="false"
    @close="globalStore.closeShowLogin"
    @closed="closedShowLogin"
  >
    <template #header="{ close, titleId, titleClass }">
      <div class="header">
        <span :id="titleId" :class="titleClass">{{
          isEdit
            ? "修改密码"
            : isAccount
            ? isPwd
              ? "密码登录"
              : "短信登录"
            : "账号注册"
        }}</span>
        <el-icon class="el-icon--left" @click="close"><Close /></el-icon>
      </div>
    </template>
    <div class="content" v-show="!isEdit">
      <div class="is_login" v-show="isAccount">
        <div class="pwd_login" v-show="isPwd">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入手机号/邮箱"
          />
          <el-input
            type="password"
            show-password
            v-model="loginForm.password"
            placeholder="请输入密码"
          >
            <template #append>
              <span @click="isEdit = true">忘记密码？</span>
            </template>
          </el-input>
        </div>
        <div class="code_login" v-show="!isPwd">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入手机号/邮箱"
          />
          <el-input v-model="loginForm.code" placeholder="请输入验证码">
            <template #append>
              <span @click="sendText(1)">{{ sendLoginText }}</span>
            </template>
          </el-input>
        </div>
        <div class="login_type">
          <span @click="isPwd = !isPwd">{{
            isPwd ? "短信登录" : "密码登录"
          }}</span>
        </div>
        <el-button @click="login" :loading="loading" type="primary"
          >登录</el-button
        >
      </div>
      <div class="is_register" v-show="!isAccount">
        <el-input
          v-model="registerForm.username"
          placeholder="请输入手机号/邮箱"
        />
        <el-input
          type="password"
          show-password
          v-model="registerForm.password"
          placeholder="请输入密码"
        />
        <el-input v-model="registerForm.code" placeholder="请输入验证码">
          <template #append>
            <span @click="sendText(2)">{{ sendRegisterText }}</span>
          </template>
        </el-input>
        <el-button @click="register" :loading="loading" type="primary"
          >注册</el-button
        >
      </div>
      <div class="tips" @click="isAccount = !isAccount">
        <span>{{ isAccount ? "还没有账号？去注册" : "已有账号，去登录" }}</span>
      </div>
    </div>
    <div class="is_edit" v-show="isEdit">
      <el-input v-model="editForm.username" placeholder="请输入手机号/邮箱" />
      <el-input
        type="password"
        show-password
        v-model="editForm.password"
        placeholder="请输入密码"
      />
      <el-input v-model="editForm.code" placeholder="请输入验证码">
        <template #append>
          <span>获取验证码</span>
        </template>
      </el-input>
      <el-button :loading="loading" type="primary">修改</el-button>
      <div class="tips" @click="isEdit = false">
        <span>返回登录</span>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import {
  authLogin,
  authLoginCode,
  authRegister,
  authSendCode,
  userInfo,
} from "@/http/api";
import { ref, computed } from "vue";
import { GlobalStore, PersistentStore } from "@/stores";
import { ElMessage } from "element-plus";

const globalStore = GlobalStore();
const persistentStore = PersistentStore();
const showLogin = computed(() => globalStore.showLogin);

const loginForm = ref({}); // 登录
const registerForm = ref({}); // 注册
const editForm = ref({}); // 修改

const loading = ref(false);

const isAccount = ref(true);
const isPwd = ref(true);
const isEdit = ref(false);
const sendRegisterText = ref("获取验证码");
const sendRegister = ref(true);
const sendLoginText = ref("获取验证码");
const sendLogin = ref(true);

const closedShowLogin = () => {
  isAccount.value = true;
  isPwd.value = true;
  isEdit.value = false;
};

// 登录
const login = async () => {
  if (isPwd) {
    if (!loginForm.value.username) {
      ElMessage.error("请输入账号");
      return;
    }
    if (!loginForm.value.password) {
      ElMessage.error("请输入密码");
      return;
    }
    loading.value = true;
    const { code, data, msg } = await authLogin({
      username: loginForm.value.username,
      password: loginForm.value.password,
    });
    loading.value = false;
    if (code == 200) {
      ElMessage.success(msg);
      persistentStore.setToken(data.access_token);
      globalStore.closeShowLogin();
      getUserInfo();
      return;
    }
    ElMessage.error(msg);
  } else {
    if (!loginForm.value.username) {
      ElMessage.error("请输入账号");
      return;
    }
    if (!loginForm.value.code) {
      ElMessage.error("请输入验证码");
      return;
    }
    loading.value = true;
    const { code, data, msg } = await authLogin({
      username: loginForm.value.username,
      code: loginForm.value.code,
    });
    loading.value = false;
    if (code == 200) {
      ElMessage.success(msg);
      persistentStore.setToken(data.access_token);
      globalStore.closeShowLogin();
      getUserInfo();
      return;
    }
    ElMessage.error(msg);
  }
};

const getUserInfo = async () => {
  const { data } = await userInfo();
  persistentStore.setUserInfo(data.user);
};

// 注册
const register = async () => {
  if (!registerForm.value.username) {
    ElMessage.error("请输入账号");
    return;
  }
  if (!registerForm.value.password) {
    ElMessage.error("请输入密码");
    return;
  }
  if (!registerForm.value.code) {
    ElMessage.error("请输入验证码");
    return;
  }
  const reg = await checkAccount(registerForm.value.username);
  if (reg == 2) {
    ElMessage.error("手机/邮箱输入不正确");
    return;
  }
  const { code, data, msg } = await authRegister({
    type: reg,
    ...registerForm.value,
  });
  if (code == 200) {
    ElMessage.success(msg);
    isPwd = !reg;
    isAccount.value = true;
    return;
  }
  ElMessage.error(msg);
};

// 校验账号
const checkAccount = (e) => {
  const regPhone = /^1[3,4,5,6,7,8,9][0-9]{9}$/;
  const regEmail = /^[A-Za-z0-9u4e00-u9fa5]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+$/;
  if (regPhone.test(e)) {
    return 0;
  }
  if (regEmail.test(e)) {
    return 1;
  }
  if (!regPhone.test(e) && !regEmail.test(e)) {
    return 2;
  }
};

// 发送验证码
const sendText = async (e) => {
  if (e == 1) {
    if (!sendLogin.value) return;
    if (!loginForm.value.username) {
      ElMessage.error("请输入手机/邮箱");
      return;
    }
    const ref = await checkAccount(loginForm.value.username);
    if (ref == 2) {
      ElMessage.error("手机/邮箱输入不正确");
      return;
    }
    const { code, data, msg } = await authSendCode({
      type: ref,
      num: loginForm.value.username,
    });
    if (code == 200) {
      ElMessage.success("发送成功");
      loginForm.value.code = data.code;
      let countDown = 60;
      sendLogin.value = false;
      const timer = setInterval(() => {
        if (countDown > 0) {
          sendLoginText.value = `${countDown}s 后重试`;
        } else {
          sendLogin.value = true;
          sendLoginText.value = "重新获取验证码";
          clearInterval(timer);
        }
        countDown--;
      }, 1000);
      return;
    }
    ElMessage.error(msg);
  }

  if (e == 2) {
    if (!sendRegister.value) return;
    if (!registerForm.value.username) {
      ElMessage.error("请输入手机/邮箱");
      return;
    }
    const ref = await checkAccount(registerForm.value.username);
    if (ref == 2) {
      ElMessage.error("手机/邮箱输入不正确");
      return;
    }
    const { code, data, msg } = await authSendCode({
      type: ref,
      num: registerForm.value.username,
    });
    if (code == 200) {
      ElMessage.success("发送成功");
      registerForm.value.code = data.code;
      let countDown = 60;
      sendRegister.value = false;
      const timer = setInterval(() => {
        if (countDown > 0) {
          sendRegisterText.value = `${countDown}s 后重试`;
        } else {
          sendRegister.value = true;
          sendRegisterText.value = "重新获取验证码";
          clearInterval(timer);
        }
        countDown--;
      }, 1000);
      return;
    }
    ElMessage.error(msg);
  }
};
</script>

<style lang="scss" scoped>
@import "index.scss";
</style>

<style>
.login_dialog {
  border-radius: 4px;
  overflow: hidden;
}
.login_dialog .el-dialog__header {
  padding: 0 !important;
  margin: 0;
}
</style>
